package com.blast.apply.presenter

import android.text.TextUtils
import android.view.View
import com.alibaba.fastjson.JSONArray
import com.blast.apply.bean.AuthBean
import com.blast.apply.http.ApplyAuthHttpUtil
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.impl.LoadingPopupView
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.FileCallback
import com.lzy.okgo.model.Response
import com.wxl.common.AppConstant
import com.wxl.common.base.AbsActivity
import com.wxl.common.http.SerialHttpCallback
import com.wxl.common.life.LifecycleManager
import com.wxl.common.room.entity.AuthorizeTermEntity
import com.wxl.common.room.entity.UnApplyBlastEntity
import com.wxl.common.room.helper.DBHelper
import com.wxl.common.util.*
import com.wxl.common.viewmodel.AbsPresenter
import io.reactivex.ObservableOnSubscribe
import kotlinx.android.synthetic.main.activity_under_apply_layout.view.*
import java.io.File

class AuthApplyPresenter : AbsPresenter() {

    lateinit var rootView:View

    private var loadDialog: LoadingPopupView? = null

    override fun onCreated(vararg args: Any) {
        rootView = args[0] as View
        rootView.underApplySubmit.setOnClickListener {
            if (isLoading()) {
                return@setOnClickListener
            }
            onSubmit()
        }
    }

    fun isLoading() : Boolean{
        return loadDialog != null && loadDialog!!.isShow
    }

    private fun onSubmit() {
        if (TextUtils.isEmpty(rootView.underApplyYzmEt.text)) {
            Toll.toll("请输入验证码")
            return
        }
        if (rootView.underApplyYzmEt.text.length != 6) {
            Toll.toll("请输入正确的验证码")
            return
        }
        KeyBoardUtil.hideSoftInput(rootView.underApplyYzmEt)
        loadDialog = XPopup.Builder(rootView.context)
            .dismissOnTouchOutside(false)
            .dismissOnBackPressed(false)
            .asLoading()
            .setTitle("正在获取授权信息...")
            .show() as LoadingPopupView
        (rootView.context as AbsActivity).addPop(loadDialog as BasePopupView)
        loadAuthData()

    }

    /**
     * 获取授权信息
     */
    private fun loadAuthData(){
        ApplyAuthHttpUtil.underApplyAuth(rootView.underApplyYzmEt.text.toString(), object :
            SerialHttpCallback<UnApplyBlastEntity.LicenseFileModel>("List") {
            override fun loadDataSuccess(datas: ArrayList<UnApplyBlastEntity.LicenseFileModel>) {
                if (datas.isNotEmpty()) {
                    if (!TextUtils.isEmpty(datas[0].filepath)) {
                        downloadLicenseFile(datas[0].filepath, datas[0])
                    } else {
                        loadDialog?.dismiss()
                        Toll.toll("验证码获取授权文件错误")
                    }
                } else {
                    loadDialog?.dismiss()
                    Toll.toll("验证码获取授权文件为空")
                }
            }

            override fun loadDataFailed(e: Throwable) {
                if(e.message != null && !TextUtils.isEmpty(e.message)){
                    Toll.toll(e.message!!)
                }
                (rootView.context as AbsActivity).dismissClearAllPop()
            }
        })
    }

    /**
     * 下载授权文件
     */
    private fun downloadLicenseFile(fileName: String, lfm: UnApplyBlastEntity.LicenseFileModel) {
        val url = AppConstant.baseIndexUrl + "uploadfile/licenseFile/" + fileName
        loadDialog?.setTitle("正在下载授权文件...")
        OkGo.get<File>(url)
            .execute(object : FileCallback(FileCommon.getLicenseFileDir().absolutePath, fileName) {
                override fun onSuccess(response: Response<File>?) {
                    if (response != null && response.isSuccessful && response.body() != null) {
                        readAuthFileData(response.body(),fileName, lfm)
                    }
                }

                override fun onError(response: Response<File>?) {
                    super.onError(response)
                    loadDialog?.dismiss()
                    Toll.toll("验证码获取授权文件出错")
                }
            })
    }

    /**
     * 读授权文件里的信息
     */
    private fun readAuthFileData(file:File,fileName: String, lfm: UnApplyBlastEntity.LicenseFileModel){
        FileCommon.readFileToText(file,
            object : ObservableUtil.Companion.OnNextCallback<String>() {
                override fun onNext(t: String) {
                    loadDialog?.setTitle("正在解析授权文件...")
                    val decode = EncryptUtils.decodeNoURL(
                        t,
                        EncryptUtils.key + rootView.underApplyYzmEt.text
                    )
                    if (!TextUtils.isEmpty(decode)) {
                        parseFileData(decode!!, fileName, lfm)
                    } else {
                        loadDialog?.dismiss()
                        Toll.toll("验证码获取授权文件信息解析错误")
                    }
                }
            })
    }


    /**
     * 解析授权文件
     */
    private fun parseFileData(
        data: String,
        fileName: String,
        lfm: UnApplyBlastEntity.LicenseFileModel
    ) {
        try {
            val unAuthData = JSONArray.parseArray(data, UnApplyBlastEntity::class.java)
            if (unAuthData.isNotEmpty()) {
                checkRepeatAdd(unAuthData, fileName, lfm)
            } else {
                loadDialog?.dismiss()
                Toll.toll("验证码获取授权文件信息解析为空")
            }
        } catch (e: Exception) {
            e.printStackTrace()
            loadDialog?.dismiss()
            Toll.toll("验证码获取授权文件信息解析不正确")
        }
    }


    /**
     * 检查是否有重复并且存入数据库
     */
    private fun checkRepeatAdd(
        data: List<UnApplyBlastEntity>,
        fileName: String,
        lfm: UnApplyBlastEntity.LicenseFileModel
    ) {
        data.takeIf {
            data[0].lgs != null && data[0].lgs.lg != null && data[0].lgs.lg[0] != null
        }?.let {
            DBHelper.queryAuthTrem(object :
                ObservableUtil.Companion.OnNextCallback<List<AuthorizeTermEntity>>() {
                override fun onNext(t: List<AuthorizeTermEntity>) {
                    checkRepeat(t, fileName,object : ObservableUtil.Companion.OnNextCallback<Boolean>(){
                        override fun onNext(repeat: Boolean) {
                            if (!repeat) {
                                val entity = AuthorizeTermEntity()
                                entity.code = rootView.underApplyYzmEt.text.toString()
                                entity.filePath = fileName
                                entity.term = data[0].lgs.lg[0].yxq
                                tryAuthTrem(entity, lfm, data)
                            } else {
                                loadDialog?.dismiss()
                                Toll.toll("该验证码已授权")
                            }
                        }
                    })
                }
            })
        }
    }


    /**
     * 保存到数据库
     */
    private fun saveAuthTrem(
        entity: AuthorizeTermEntity,
        lfm: UnApplyBlastEntity.LicenseFileModel,
        data: List<UnApplyBlastEntity>
    ) {
        loadDialog?.setTitle("保存该授权文件信息...")
        DBHelper.insertAuthTrem(object : ObservableUtil.Companion.OnNextCallback<Boolean>() {
            override fun onNext(t: Boolean) {
                saveUnApplyBlastEntity(lfm, data)
            }
        }, entity)
    }


    /**
     * 保存授权信息
     */
    private fun saveUnApplyBlastEntity(
        lfm: UnApplyBlastEntity.LicenseFileModel,
        data: List<UnApplyBlastEntity>
    ) {
        data.forEach {
            it.licenseFileModel = lfm
            it.isAuth = 1
        }
        DBHelper.insertUnApplyBlastData(object :
            ObservableUtil.Companion.OnNextCallback<Boolean>() {
            override fun onNext(t: Boolean) {
                loadDialog?.dismiss()
                Toll.toll("授权成功。")
                val ab = AuthBean()
                ab.isAuth = 1
                LifecycleManager.manager.refreshLiveData(ab)
            }
        }, *data.toTypedArray())
    }


    /**
     * 尝试授权这些信息
     */
    private fun tryAuthTrem(
        entity: AuthorizeTermEntity,
        lfm: UnApplyBlastEntity.LicenseFileModel,
        datas: List<UnApplyBlastEntity>
    ) {
        loadDialog?.setTitle("尝试授权该文件...")
        ApplyAuthHttpUtil.authTrem(
            entity.code,
            entity.term,
            entity.filePath,
            object : SerialHttpCallback<String>("") {
                override fun loadDataSuccess(data: String?) {
                    entity.isAuth = 1
                    saveAuthTrem(entity, lfm, datas)
                }

                override fun loadDataFailed(e: Throwable) {
                    saveAuthTrem(entity, lfm, datas)
                    loadDialog?.dismiss()
                    Toll.toll("尝试授权失败")
                }
            })
    }


    /**
     * 检查重复
     */
    private fun checkRepeat(t: List<AuthorizeTermEntity>, fileName: String, callback: ObservableUtil.Companion.OnNextCallback<Boolean>) {
        loadDialog?.setTitle("正在检查授权文件是否重复...")
        ObservableUtil.doNext(ObservableOnSubscribe<Boolean> { oos->
            if (t.isNotEmpty()) {
                t.forEach {
                    if (TextUtils.equals(fileName, it.filePath) && it.isAuth == 1) {
                        oos.onNext(true)
                        return@forEach
                    }
                }
                oos.onNext(false)
            }
        },callback)
    }

}